<template>
  <div class="infinite" ref="container" :style="{ height: height }">
    <div class="inner" ref="inner">
      <!-- 列表标题 -->
      <slot name="title"></slot>
      <!-- 这里放列表 -->
      <slot></slot>
      <!-- 加载中的动画 -->
      <slot name="loading" v-if="loading"></slot>
      <!-- 加载完成的动画 -->
      <slot name="nomore" v-if="nomore"></slot>
    </div>
  </div>
</template>
<script>
export default {
  name: 'infinite-scroll',
  props: {
    height: {
      type: String,
      default: '100%',
    },
    loading: {
      type: Boolean,
      default: false,
    },
    nomore: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      containerHeight: 0,
      innerHeight: 0,
    };
  },
  created() {
  },
  mounted() {
    let that = this;
    setTimeout(() => {
      that.$nextTick(() => {
        var tryBind = function () {
          // console.log(123);
          try {
            that.containerHeight = that.$refs.container.clientHeight;
            that.innerHeight = that.$refs.inner.offsetHeight;
            console.log(that.containerHeight, that.innerHeight);
            document.addEventListener('scroll', that.initScroll);
          } catch (e) {
            setTimeout(tryBind, 100);
          }
        };
        tryBind();
      });
    }, 2000);
  },
  methods: {
    initScroll(e) {
      // console.log("====initScroll====");
      try {
        if (this.loading || this.nomore) return;
        this.innerHeight = this.$refs.inner.offsetHeight;
        // console.log(window);
        let scrollTop = window.scrollY;
        // console.log(scrollTop, this.containerHeight, this.innerHeight);
        if (scrollTop + this.containerHeight >= this.innerHeight) {
          // console.log("-----------------触底了-------------");
          this.$emit('loadBottom');
        }
      } catch (e) {
        // console.log(e);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.infinite {
  width: 100%;
  // background-color: skyblue;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; // 解决iOS滚动问题
  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
